package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.CheckInConfigMapper;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.mapper.ContractMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 入住信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-07
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private IBedService iBedService;
    @Autowired
    private IElderService iElderService;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ICheckInService iCheckInService;
    @Autowired
    private ICheckInConfigService iCheckInConfigService;
    @Autowired
    private IContractService iContractService;

    /**
     * 查询入住信息
     *
     * @param id 入住信息主键
     * @return 入住信息
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住信息列表
     *
     * @param checkIn 入住信息
     * @return 入住信息
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住信息
     *
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住信息
     *
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住信息
     *
     * @param ids 需要删除的入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息信息
     *
     * @param id 入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 入住申请
     *
     * @param checkInApplyDto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        // 1.判断老人是否已入住
        Elder elder = iElderService.lambdaQuery().eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo()).eq(Elder::getStatus, 1).one();
        if (ObjectUtil.isNotEmpty(elder)) {
            throw new BaseException("老人已入住");
        }
        // 2.更新床位状态
        Bed bed = iBedService.lambdaQuery().eq(Bed::getId, checkInApplyDto.getCheckInConfigDto().getBedId()).one();
        bed.setBedStatus(1);
        boolean result = iBedService.updateById(bed);
        if (!result) {
            throw new BaseException("该床位已有人入住，请重新选择！");
        }
        // 3.更新或新增老人信息
        elder = insertOrUpdate(bed, checkInApplyDto.getCheckInElderDto());
        // 4. 新增入住合同
        // 生成合同编号
        String contractNo = "HT" + CodeGenerator.generateContractNumber();
        insertContract(contractNo, elder, checkInApplyDto);
        // 5. 新增入住信息
        CheckIn checkIn = insertCheckInInfo(elder, checkInApplyDto);
        // 6. 新增入住配置
        insertCheckInConfig(checkIn.getId(), checkInApplyDto);
    }

    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
//        SELECT ci.id as ciid, ci.elder_name, ci.id_card_no, ci.remark, ci.start_date, ci.end_date, e.id as eid,
//        e.birthday, e.sex, e.phone, e.address, e.image, e.id_card_national_emblem_img, e.id_card_portrait_img, e.age, cig.id
//        as cigid,
//        cig.nursing_level_id, cig.nursing_level_name, cig.fee_start_date, cig.fee_end_date, cig.deposit, cig.nursing_fee, cig.bed_fee, cig.insurance_payment, cig.government_subsidy, cig.other_fees, cig.sort_order
//        as cig_sort_order, cig.create_time as cig_create_time, cig.update_time as cig_update_time, cig.create_by as
//        cig_create_by, cig.update_by as cig_update_by, cig.check_in_id, ci.bed_number, ct.id as ctid,
//        ct.create_by, ct.create_time, ct.update_time, ct.elder_id, ct.contract_number, ct.contract_name, ct.agreement_path, ct.third_party_phone, ct.third_party_name, ct.elder_name
//        as ct_elder_name, ct.start_date as ct_start_date, ct.end_date as ct_end_date,
//        ct.status, ct.sign_date, ct.sort_order as ct_sort_order FROM check_in ci LEFT JOIN elder e ON ci.elder_id = e.id
//        LEFT JOIN check_in_config cig ON ci.id = cig.check_in_id LEFT JOIN contract ct ON e.id = ct.elder_id WHERE ci.
//        id = #{id}
        // 1.查出所有数据
        CheckIn checkIn = iCheckInService.lambdaQuery().eq(CheckIn::getId, id)
                .one();
        Elder elder = iElderService.lambdaQuery().eq(Elder::getId, checkIn.getElderId())
                .one();
        CheckInConfig checkInConfig = iCheckInConfigService.lambdaQuery().eq(CheckInConfig::getCheckInId, checkIn.getId())
                .one();
        Contract contract = iContractService.lambdaQuery().eq(Contract::getElderId, elder.getId())
                .one();
        // 2.封装成vo，并组装成CheckInDetailVo
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        // 2.1 封装入住老人信息
        if (ObjectUtil.isNotEmpty(elder)){
            CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
            checkInDetailVo.setCheckInElderVo(checkInElderVo);
        }
        // 2.2 封装入住老人家庭关系
        String remark = checkIn.getRemark();
        if (ObjectUtil.isNotEmpty(remark)){
            JSONArray jsonArray = JSONUtil.parseArray(remark);
            List<ElderFamilyVo> elderFamilyVos = JSONUtil.toList(jsonArray, ElderFamilyVo.class);
            checkInDetailVo.setElderFamilyVoList(elderFamilyVos);
        }
        // 2.3 封装入住老人入住配置信息
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        if (ObjectUtil.isNotEmpty(checkInConfig)){
            BeanUtil.copyProperties(checkInConfig, checkInConfigVo);
        }
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);

        // 2.4 封装入住老人入住合同信息
        if (ObjectUtil.isNotEmpty(contract)){
             checkInDetailVo.setContract(contract);
        }

        return checkInDetailVo;
    }

    /**
     * 新增入住配置
     *
     * @param checkInId
     * @param checkInApplyDto
     */
    private void insertCheckInConfig(Long checkInId, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInApplyDto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     *
     * @param elder
     * @param checkInApplyDto
     * @return
     */
    private CheckIn insertCheckInInfo(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        // 老人信息
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        // 入住信息
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        // 床位信息
        checkIn.setBedNumber(elder.getBedNumber());
        // 家属信息
        if (ObjectUtil.isNotEmpty(checkInApplyDto.getElderFamilyDtoList())) {
            checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        }
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增入住合同
     *
     * @param contractNo
     * @param elder
     * @param checkInApplyDto
     */
    private void insertContract(String contractNo, Elder elder, CheckInApplyDto checkInApplyDto) {
        Contract contract = BeanUtil.toBean(checkInApplyDto.getCheckInContractDto(), Contract.class);
        // 合同编号
        contract.setContractNumber(contractNo);
        // 老人信息
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        // 状态、开始时间、结束时间
        // 签约时间小于等于当前时间，合同生效中
        LocalDateTime checkInStartTime = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = checkInApplyDto.getCheckInConfigDto().getEndDate();
        Integer status = checkInStartTime.isBefore(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);
        contractMapper.insert(contract);
    }

    /**
     * 更新或新增老人信息
     *
     * @param bed
     * @param checkInElderDto
     * @return
     */
    private Elder insertOrUpdate(Bed bed, CheckInElderDto checkInElderDto) {
        Elder elder = BeanUtil.toBean(checkInElderDto, Elder.class);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);
        //判断老人是否存在
        Elder elderInDB = iElderService.lambdaQuery().eq(Elder::getIdCardNo, elder.getIdCardNo()).ne(Elder::getStatus, 1).one();
        if (ObjectUtil.isNotEmpty(elderInDB)) {
            iElderService.updateElder(elder);
        } else {
            iElderService.insertElder(elder);
        }
        return elder;
    }

}
